package org.xxpay.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.apibase.service.IAPIOrderService;
import org.xxpay.apibase.vo.ApiPayOrder;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.entity.PayPassageAccount;
import org.xxpay.pay.mq.BaseNotify4CashColl;
import org.xxpay.pay.mq.BaseNotify4MchPay;
import org.xxpay.pay.service.CommonService;

@Service
public class APIOrderServiceImpl implements IAPIOrderService {

    @Autowired private CommonService commonService;

    @Autowired
    private BaseNotify4MchPay baseNotify4MchPay;

    @Override
    public void updateOrderIng2Success(String payOrderId, String channelOrderNo) {

        commonService.payOrderService.updateStatus4Success(payOrderId, channelOrderNo); //更新订单为成功
    }

    @Override
    public void updateOrderReady2Ing(String payOrderId, String channelOrderNo) {

        commonService.payOrderService.updateStatus4Ing(payOrderId, channelOrderNo);
    }

    @Override
    public ApiPayOrder getByPayOrderId(String payOrderId) {

        ApiPayOrder result = new ApiPayOrder();
        try {
            BeanUtils.copyProperties(commonService.payOrderService.findByPayOrderId(payOrderId), result);
            return result;

        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public JSONObject getPayParamJSONByOrderId(String payOrderId) {

        PayOrder payOrder = commonService.payOrderService.selectPayOrder(payOrderId);
        if(payOrder == null) return null;

        String payParam = "";
        PayPassageAccount payPassageAccount = commonService.payPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null) throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST);

        payParam = payPassageAccount.getParam();
        if(StringUtils.isBlank(payParam)) throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST); //仍然为空，说明配置有误

        return JSONObject.parseObject(payParam);

    }

    @Override
    public void notifySuccess2SubMch(String payOrderId) {
        baseNotify4MchPay.doNotify(payOrderId, true);
    }

    @Override
    public String genReturnUrlByOrderId(String payOrderId) {
        return baseNotify4MchPay.createNotifyUrl(commonService.payOrderService.findByPayOrderId(payOrderId), "1");
    }

    @Override
    public int saveTopayUrl(String payOrderId, String topayUrl) {
        return commonService.payOrderService.saveTopayUrl(payOrderId, topayUrl);
    }
}
